package com.example.demo.generator.service;

import com.example.demo.generator.codegen.SpringBootCodeGeneratorAdapter;
import com.example.demo.generator.codegen.exception.SqlParseException;
import com.example.demo.generator.codegen.model.ClassInfo;
import com.example.demo.generator.codegen.model.ParamInfo;
import com.example.demo.generator.dto.SqlParseRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * Facade that bridges REST requests and the embedded SpringBootCodeGenerator adapter.
 */
@Service
public class CodeGeneratorFacade {

    /**
     * SQL 解析适配器。
     */
    private final SpringBootCodeGeneratorAdapter adapter;

    public CodeGeneratorFacade(SpringBootCodeGeneratorAdapter adapter) {
        this.adapter = adapter;
    }

    /**
     * 根据请求参数解析 SQL 并返回元数据信息。
     *
     * @param request SQL 解析请求
     * @return 表结构描述
     * @throws SqlParseException 解析失败
     */
    public ClassInfo previewSql(SqlParseRequest request) throws SqlParseException {
        ParamInfo paramInfo = new ParamInfo();
        paramInfo.setTableSql(request.getSql());
        paramInfo.setOptions(buildOptions(request));
        boolean useFallback = request.isFallback();

        String mode = request.getMode().toLowerCase(Locale.ROOT);
        switch (mode) {
            case "create":
                return adapter.parseCreateTable(paramInfo);
            case "select":
                return adapter.parseSelectSql(paramInfo);
            case "fallback":
                useFallback = true;
                break;
            default:
                throw new IllegalArgumentException("不支持的解析模式: " + request.getMode());
        }
        return useFallback ? adapter.fallbackProcessTable(paramInfo) : adapter.parseCreateTable(paramInfo);
    }

    /**
     * 从请求构造解析选项。
     *
     * @param request SQL 解析请求
     * @return 解析选项
     */
    private Map<String, Object> buildOptions(SqlParseRequest request) {
        Map<String, Object> options = new HashMap<>();
        if (StringUtils.isNotBlank(request.getIgnorePrefix())) {
            options.put("ignorePrefix", request.getIgnorePrefix());
        }
        if (StringUtils.isNotBlank(request.getNameCaseType())) {
            options.put("nameCaseType", request.getNameCaseType());
        }
        return options;
    }
}
